<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';

import {
  Button,
  Checkbox,
  CheckboxGroup,
  Divider,
  Input,
  message,
  Popover,
  Radio,
  RadioButton,
  RadioGroup,
} from 'ant-design-vue';

import { updateCalendarRoomStock } from '#/api';
import { useRoomList } from '#/hooks/useRoomList';

import CalendarList from './components/CalendarList.vue';
import DateSelect from './components/DateSelect.vue';

const { roomList, fetchRoomList } = useRoomList();

interface FormDataType {
  remainCountType: number | string;
  addRemainCount: number | string;
  reduceRemainCount: number | string;
  remainCount: number | string;
  roomStatus: number | string;
  limitedType: number | string;
  weekType: number[] | string[];
  allWeekType: boolean;
  timeType: number | string;
  roomSelect: number[] | string[];
  allRoomSelect: boolean;
}

const formData = ref<FormDataType>({
  remainCountType: 0, // 剩余房量
  addRemainCount: '', // 增加房量
  reduceRemainCount: '', // 减少房量
  remainCount: '', // 设置固定房量
  roomStatus: 0, // 房态
  limitedType: 0, // 限量类型
  weekType: ['1', '2', '3', '4', '5', '6', '0'], // 星期类型
  allWeekType: true, // 是否全选
  timeType: '1', // 时间类型 1时间区间 2日历选择模式
  roomSelect: [], // 选择的房型
  allRoomSelect: false, // 是否全选房型
});

// 是否使用所有日期
const scopeChecked = ref(false);

const optionsWeek = [
  { label: '周一', value: '1' },
  { label: '周二', value: '2' },
  { label: '周三', value: '3' },
  { label: '周四', value: '4' },
  { label: '周五', value: '5' },
  { label: '周六', value: '6' },
  { label: '周日', value: '0' },
];

// 全选星期事件
const handleAll = (e: any) => {
  Object.assign(formData.value, {
    weekType: e.target.checked ? optionsWeek.map((item) => item.value) : [],
  });
};
// 监听是否全选事件
watch(
  () => formData.value.weekType,
  (val) => {
    formData.value.allWeekType = val.length === optionsWeek.length;
  },
  { immediate: true },
);

// 房型全选事件
const handleRoomAll = (e: any) => {
  Object.assign(formData.value, {
    roomSelect: e.target.checked ? roomList.value.map((item) => item.id) : [],
  });
};
watch(
  () => formData.value.roomSelect,
  (val) => {
    formData.value.allRoomSelect = val.length === roomList.value.length;
  },
);

// 排除字段 防止eslint报错提示
type StringFields = Exclude<
  keyof FormDataType,
  'allRoomSelect' | 'allWeekType' | 'roomSelect' | 'weekType'
>;

// 限制输入长度的函数
const handleInput = (e: Event, field: StringFields) => {
  let value = (e.target as HTMLInputElement).value;
  // 只保留数字部分
  value = value.replaceAll(/\D/g, '');
  if (value.length > 3) {
    value = value.slice(0, 3);
    // 手动更新输入框的值
    (e.target as HTMLInputElement).value = value;
  }
  formData.value[field] = value;
};
// 选中的日期数据
const dateArr = ref<string[]>([]);
// 日历模式选中日期事件
const dateChange = (val: string[]) => {
  dateArr.value = val || [];
};

const loading = ref(false);

// 保存事件
const submit = async () => {
  try {
    if (formData.value.roomSelect.length === 0) {
      return message.error('请选择房型');
    }
    if (!scopeChecked.value && dateArr.value.length === 0) {
      return message.error('请选择日期');
    }
    if (loading.value) return;
    loading.value = true;
    let quotaCount;
    switch (formData.value.remainCountType) {
      case 0: {
        quotaCount = '';
        break;
      }
      case 1: {
        quotaCount = formData.value.addRemainCount;
        break;
      }
      case 2: {
        quotaCount = formData.value.reduceRemainCount;
        break;
      }
      case 3: {
        quotaCount = formData.value.remainCount;
        break;
      }
    }
    await updateCalendarRoomStock({
      isAllTime: scopeChecked.value,
      operateType:
        formData.value.remainCountType === 0
          ? null
          : formData.value.remainCountType,
      quotaCount,
      roomStatus:
        formData.value.roomStatus === 0 ? null : formData.value.roomStatus,
      roomTypeId: formData.value.roomSelect || [],
      saleMode:
        formData.value.limitedType === 0 ? null : formData.value.limitedType,
      timeList: dateArr.value,
    });
    message.success('保存成功');
    loading.value = false;
    Object.assign(formData.value, {
      roomSelect: [],
      remainCountType: 0, // 剩余房量
      addRemainCount: '', // 增加房量
      reduceRemainCount: '', // 减少房量
      remainCount: '', // 设置固定房量
      roomStatus: 0, // 房态
      limitedType: 0, // 限量类型
      weekType: ['1', '2', '3', '4', '5', '6', '0'], // 星期类型
      timeType: '1', // 时间类型 1时间区间 2日历选择模式
    });
  } catch (error) {
    loading.value = false;
    console.error('保存失败：', error);
  }
};

onMounted(async () => {
  await fetchRoomList({
    enableStatus: true,
    name: '',
  });
});
</script>

<template>
  <div class="flex h-[100%] w-[100%] flex-col overflow-auto p-5 pt-4">
    <div class="mb-4 text-xl font-bold">批量修改房量房态</div>
    <div class="card-box w-full p-5 pt-4">
      <div class="mb-3 text-base font-bold">选择房型</div>
      <div class="card-box rounded-md">
        <div class="flex min-h-[50px] items-center px-5 py-3">
          <Checkbox
            v-model:checked="formData.allRoomSelect"
            @change="handleRoomAll"
          >
            <div class="text flex items-center">
              全选
              <p v-if="formData.roomSelect.length > 0" class="ml-2">
                (已选择<span class="text-primary pl-1">
                  {{ formData.roomSelect.length }}
                </span>
                个房型)
              </p>
            </div>
          </Checkbox>
        </div>
        <div class="max-h-[240px] overflow-auto px-5">
          <CheckboxGroup
            v-model:value="formData.roomSelect"
            class="flex flex-wrap"
            name="roomSelect"
          >
            <div v-for="item in roomList" :key="item.id" class="w-full">
              <Divider class="m-0" />
              <Checkbox
                :value="item.id"
                class="mr-2 flex min-h-[50px] items-center py-3"
              >
                <span class="text">{{ item.nameZh }}</span>
              </Checkbox>
            </div>
          </CheckboxGroup>
        </div>
      </div>

      <div class="mb-3 mt-4 text-base font-bold">选择日期</div>
      <div class="card-box rounded-md">
        <div class="flex min-h-[50px] flex-wrap items-center px-5 py-3">
          <RadioGroup v-model:value="formData.timeType">
            <RadioButton class="h-auto py-1" value="1">
              <span :class="[formData.timeType === '1' ? 'font-bold' : 'text']">
                多段模式
              </span>
            </RadioButton>
            <RadioButton class="h-auto py-1" value="2">
              <span :class="[formData.timeType === '2' ? 'font-bold' : 'text']">
                日历模式
              </span>
            </RadioButton>
          </RadioGroup>
        </div>
        <Divider class="m-0" />
        <div v-if="formData.timeType === '1'" class="w-full">
          <DateSelect
            v-model:scope-checked="scopeChecked"
            :select-week="formData.weekType"
            @change="dateChange"
          />
        </div>
        <div v-else class="w-full">
          <CalendarList :select-week="formData.weekType" @change="dateChange" />
        </div>
        <Divider class="m-0" />
        <div class="flex min-h-[50px] flex-wrap items-center px-5">
          <div class="w-[90px] py-1 pr-2 opacity-60">适用星期</div>
          <div class="flex-auto py-2">
            <CheckboxGroup v-model:value="formData.weekType" name="weekType">
              <Checkbox
                v-for="item in optionsWeek"
                :key="item.value"
                :value="item.value"
                class="mr-2 py-1"
              >
                <span class="text">{{ item.label }}</span>
              </Checkbox>
            </CheckboxGroup>
            <Checkbox
              v-model:checked="formData.allWeekType"
              @change="handleAll"
            >
              <span class="text">全选</span>
            </Checkbox>
          </div>
        </div>
      </div>

      <div class="mb-3 mt-4 text-base font-bold">设置房态</div>
      <div
        class="card-box flex min-h-[50px] flex-wrap items-center rounded-md px-5 py-1"
      >
        <RadioGroup v-model:value="formData.roomStatus" name="roomStatus">
          <Radio :value="0" class="py-1"><span class="text">不变</span></Radio>
          <Radio :value="1" class="py-1"><span class="text">有房</span></Radio>
          <Radio :value="2" class="py-1"><span class="text">满房</span></Radio>
        </RadioGroup>
      </div>

      <div class="mb-3 mt-4 text-base font-bold">设置房量</div>
      <div class="card-box rounded-md">
        <div class="flex min-h-[50px] flex-wrap items-center px-5">
          <div class="w-[140px] py-1 pr-2 opacity-60">限量</div>
          <div class="flex-auto py-2">
            <RadioGroup v-model:value="formData.limitedType" name="limitedType">
              <Radio :value="0" class="py-1">
                <span class="text">不变</span>
              </Radio>
              <Radio :value="1" class="py-1">
                <Popover content="仅售卖保留房间数，保留房售完停止售卖">
                  <span
                    class="text underline decoration-gray-300 decoration-dashed underline-offset-4"
                  >
                    限量
                  </span>
                </Popover>
              </Radio>
              <Radio :value="2" class="py-1">
                <Popover content="按照保留房不限畅卖">
                  <span
                    class="text underline decoration-gray-300 decoration-dashed underline-offset-4"
                  >
                    FreeSale
                  </span>
                </Popover>
              </Radio>
            </RadioGroup>
          </div>
        </div>
        <Divider class="m-0" />
        <div class="flex min-h-[50px] flex-wrap items-center px-5">
          <div class="w-[140px] py-1 pr-2 opacity-60">剩余房量</div>
          <div class="flex-auto py-1">
            <RadioGroup
              v-model:value="formData.remainCountType"
              name="remainCountType"
            >
              <Radio :value="0" class="py-1">
                <span class="text">不变</span>
              </Radio>
              <Radio :value="1" class="py-1">
                <span class="text">增加</span>
                <Input
                  v-model:value="formData.addRemainCount"
                  class="ml-2 w-[100px]"
                  suffix="间"
                  type="number"
                  @focus="formData.remainCountType = 1"
                  @input="(e) => handleInput(e, 'addRemainCount')"
                />
              </Radio>
              <Radio :value="2" class="py-1">
                <span class="text">减少</span>
                <Input
                  v-model:value="formData.reduceRemainCount"
                  class="ml-2 w-[100px]"
                  suffix="间"
                  type="number"
                  @focus="formData.remainCountType = 2"
                  @input="(e) => handleInput(e, 'reduceRemainCount')"
                />
              </Radio>
              <Radio class="py-1" value="3">
                <span class="text">设置为</span>
                <Input
                  v-model:value="formData.remainCount"
                  class="ml-2 w-[100px]"
                  suffix="间"
                  type="number"
                  @focus="formData.remainCountType = 3"
                  @input="(e) => handleInput(e, 'remainCount')"
                />
              </Radio>
            </RadioGroup>
          </div>
        </div>
      </div>
      <Button
        :disabled="
          formData.roomSelect.length === 0 ||
          (!scopeChecked && dateArr.length === 0)
        "
        :loading="loading"
        class="mb-4 mt-5 h-auto w-auto px-14 py-2"
        type="primary"
        @click="submit"
      >
        保存
      </Button>
    </div>
  </div>
</template>
<style scoped lang="scss">
.text {
  color: hsl(var(--card-foreground));
}
</style>
